import { app, BrowserWindow, ipcMain } from 'electron'
import { electronApp, optimizer } from '@electron-toolkit/utils'
import fs from 'fs'
import { selectLocalFilePath, getAllImageUrls, copyTextToClipboard, checkForUpdates, downloadSoftware, setPictureAsWallpaper } from './operation'
import myWindow from './myWindow'
let { mainWindow, childWindow } = myWindow()

const writeFile = (_, data) => {
  fs.writeFileSync('D:hello.txt', data, 'utf-8')
}

app.whenReady().then(() => {
  electronApp.setAppUserModelId('com.electron')
  app.on('browser-window-created', (_, window) => {
    optimizer.watchWindowShortcuts(window)
  })
  ipcMain.on('ping', () => console.log('pong'))
  mainWindow()
  ipcMain.on("save-file", writeFile)
  // 获取版本号
  ipcMain.handle('get-version', () => {
    return app.getVersion()
  })
  ipcMain.handle('new-open', (_, param) => {
    childWindow(param)
  })
  ipcMain.handle('select-local-file-path', selectLocalFilePath)
  ipcMain.handle('get-all-image-urls', (_, src: string) => {
    return getAllImageUrls(src)
  })
  ipcMain.handle('copy-text-to-clipboard', (_, src: string) => {
    copyTextToClipboard(src)
  })
  // 检测软件更新
  ipcMain.handle('update-software', (_, url: string) => {
    return checkForUpdates(url)
  })
  // 下载更新
  ipcMain.handle('download-update', (event, param: any) => {
    // 获取当前窗口
    const currentWindow = BrowserWindow.fromWebContents(event.sender)!
    return downloadSoftware(currentWindow, param.download, param.fileName, param.savePath)
  })
  // 设置壁纸
  ipcMain.handle('set-wallpaper', (_, params: any) => {
    setPictureAsWallpaper(params.path)
  })

  app.on('activate', function () {
    if (BrowserWindow.getAllWindows().length === 0) mainWindow()
  })
})

// 监听store仓库变化，广播给其他窗口
ipcMain.on('update-storage', (event, key) => {
  for (const currentWin of BrowserWindow.getAllWindows()) {
    const webContentsId = currentWin.webContents.id
    if (webContentsId !== event.sender.id) {
      currentWin.webContents.send('update-storage', key)
    }
  }
})


app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit()
  }
})
